<?php
namespace yphp;
/**
 * Class Db
 * @package yphp
 * 数据库类
 */
final class Db extends DbBase
{
    # 地址
    private $address;
    # 数据库
    private $dbname;

    // 构造函数
    function construct($key = 0)
    {
        $this->address = Config::database('db'.'.'.$key);
    }

    // 指定数据库
    function dbn($dbname)
    {
        is_null($dbname) && $dbname = self::defaultDbn($this->address);
        $this->dbname === $dbname || $this->dbname = $dbname;
        return $this;
    }

    // 获取默认表前缀
    final private static function defaultDth($address)
    {
        $link = Config::databaseSpot('link',$address);
        return key_exists('dth',$link) ? $link['dth'] : null;
    }

    // 获取默认数据库
    final private static function defaultDbn($address)
    {
        $dbn = Config::databaseSpot('link',$address);

        if (key_exists('dbn',$dbn)){
            return $dbn['dbn'];
        }

        throw new \Exception('请填写数据库dbn名');
    }

    // 指定表
    function table($table,$dth)
    {
        $table = is_null($dth) ? self::defaultDth($this->address).$table : $dth.$table;
        return $this->componet($table,self::defaultDth($this->address));
    }

    // 查询
    function select($isArr = false)
    {
        list($sql, $bind) = $this->selectSql();
        return $this->query($sql,$bind,$isArr);
    }

    // 更新
    function update()
    {
        list($sql, $bind) = $this->updateSql();
        return $this->execute($sql,$bind);
    }

    // 删除
    function delete()
    {
        list($sql, $bind) = $this->deleteSql();
        return $this->execute($sql,$bind);
    }

    //  插入
    function insert()
    {
        list($sql, $bind) = $this->insertSql($this->address,$this->dbname);
        return $this->execute($sql,$bind,true);
    }

    // 增删改执行SQL
    function execute($sql, $bind = null, $insert = false)
    {
        return self::modify(self::setDbn($this->address, $this->dbname), $sql, $bind, $insert);
    }

    // 查询
    function query($sql, $bind = null, $rArr = false)
    {
        return self::inQuery(self::setDbn($this->address, $this->dbname), $sql, $bind, $rArr);
    }

}